package cn.chengpengper.rpc.reflect.bytebuddy;

import cn.chengpengper.rpc.reflect.api.ReflectInvoker;
import cn.chengpengper.rpc.spi.annotation.SpiClass;
import lombok.extern.slf4j.Slf4j;
import net.bytebuddy.ByteBuddy;

import java.lang.reflect.Method;

/**
 * @author chengpeng.hu
 */
@Slf4j
@SpiClass
public class ByteBuddyReflectInvoker implements ReflectInvoker {
    @Override
    public Object invokeMethod(Object serviceBean, Class<?> serviceClass, String methodName, Class<?>[] parameterTypes, Object[] parameters) throws Throwable {
        log.info("基于ByteBuddy的invokeMethod");
        Class<?> childClass = new ByteBuddy().subclass(serviceClass)
                .make()
                .load(ByteBuddyReflectInvoker.class.getClassLoader())
                .getLoaded();
        Object instance = childClass.getDeclaredConstructor().newInstance();
        Method method = childClass.getMethod(methodName, parameterTypes);
        method.setAccessible(true);
        return method.invoke(instance, parameters);

    }
}
